/*
 * Copyright 2007 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package bw.os;

import java.util.zip.*;
import java.io.*;
import java.math.*;
import java.security.*;

public class PersistentObjectHandler 
{
    public static final String FILE_PREFIX = "os-";
    public static final String FILE_EXT = ".obj";

    public PersistentObjectHandler ()
    {
        //nothing. This class provides a base set of 
        //utility methods common to all classes that read and
        //write persistent objects so that they do it in the same way
    }

    protected String makeFilename ( String key )
    {
        String hashedKey = hashKey( key );

        return ( FILE_PREFIX + hashedKey + FILE_EXT );
    }

    private String hashKey ( String key )
    {
        String hashed = "";

        try 
        {
            MessageDigest md5 = MessageDigest.getInstance( "MD5" );
            md5.update( key.getBytes() );
            BigInteger hash = new BigInteger( 1, md5.digest() );
            hashed = hash.toString( 16 );
        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
            hashed = String.valueOf( key.hashCode() );
        }
        
        return hashed;    
    }

    /*    protected String extractKey ( String filename )
    {
        return filename.substring( FILE_PREFIX.length(), filename.indexOf( FILE_EXT ) );
    }*/

    protected Object getObjectFromStream ( InputStream in )
        throws Exception
    {
        ObjectInputStream ois = getObjectInputStream( in );
        Object obj = ois.readObject();
        ois.close();

        return obj;
    }

    protected ObjectInputStream getObjectInputStream ( InputStream in )
        throws Exception
    {
        return new ObjectInputStream( new GZIPInputStream( in ) );
    }

    protected ObjectOutputStream getObjectOutputStream ( OutputStream out )
        throws Exception
    {
        return new ObjectOutputStream( new GZIPOutputStream( out ) );
    }
}